// pages/addRecord/addRecord.ts
Page({
    data: {
      name: '',
      quantity: '',
      unitPrice: '',
      totalPrice: 0,
      date: new Date().toISOString().substring(0, 10),
      customerName: '', // 添加客户名称字段
      customerList: [] as string[], // 存储所有客户名称
      filteredCustomerList: [] as string[], // 存储筛选后的客户名称
      showDropdown: false // 控制下拉框的显示
    },
  
    onLoad() {
      this.loadCustomers();
    },
  
    // 加载客户列表
    loadCustomers() {
      const users = wx.getStorageSync('users') || [];
      const customerList = users.map((user: CustomerInfo) => user.name);
      this.setData({
        customerList,
        filteredCustomerList: customerList
      });
    },
  
    // 更新输入值
    onInputChange(e: WechatMiniprogram.Input) {
      const { field } = e.target.dataset as { field: string };
      const value = e.detail.value;
      this.setData({
        [field]: value
      }, () => {
        if (field === 'quantity' || field === 'unitPrice') {
          this.calculateTotalPrice();
        }
        if (field === 'customerName') {
          this.filterCustomerList(value);
        }
      });
    },
  
    // 计算总价
    calculateTotalPrice() {
      const { quantity, unitPrice } = this.data;
      const totalPrice = parseFloat(quantity) * parseFloat(unitPrice);
      this.setData({
        totalPrice: isNaN(totalPrice) ? 0 : totalPrice
      });
    },
  
    // 筛选客户列表
    filterCustomerList(value: string) {
      const filtered = this.data.customerList.filter(customer => customer.includes(value));
      this.setData({
        filteredCustomerList: filtered,
        showDropdown: filtered.length > 0
      });
    },
  
    // 选择客户
    onSelectCustomer(e: WechatMiniprogram.TouchEvent) {
      const customerName = e.currentTarget.dataset.customer;
      this.setData({
        customerName,
        showDropdown: false
      });
    },
  
    // 提交记录
    onSubmit() {
      const { name, quantity, unitPrice, totalPrice, date, customerName } = this.data;
      if (name && quantity && unitPrice && customerName) { // 确保客户名称也被填写
        const record: OutRecord = {
          name,
          quantity: parseFloat(quantity),
          unitPrice: parseFloat(unitPrice),
          totalPrice,
          date,
          customerName // 添加客户名称到记录中
        };
        const records = wx.getStorageSync('outRecords') || [];
        records.push(record);
        wx.setStorageSync('outRecords', records);
        wx.showToast({
          title: '记录添加成功',
          icon: 'success',
          duration: 2000,
          complete: () => {
            wx.navigateBack();
          }
        });
      } else {
        wx.showToast({
          title: '请完整填写所有字段',
          icon: 'none'
        });
      }
    }
  });
  